/* eslint-disable react/sort-comp */
/* eslint-disable prefer-const */
/**
 * 报销单费用详情 - 费用列表
 */
import React from "react";
import { connect } from "react-redux";
import {
  messages,
  queryCurrencyPrecision,
  getQueryUrlParam,
  deepFullCopy,
  currencyPrecisionCal,
  invoiceAmountChange,
  removeArryItem,
  addCalculate,
} from "share/common";
import {
  Popconfirm,
  Icon,
  Popover,
  message,
  Input,
  Select,
  Button,
  Modal,
} from "antd";
import config from 'config';

import errorMessage from "share/errorMessage";
import CustomTable from "components/custom-table";
import Condition from "components/condition";
const { If, Else } = Condition;

import expenseService from "containers/my-account/expense.service";
import expenseReportService from "containers/expense-report/expense-report.service";
import { Chooser } from "components";
import SelectByBtn from "components/template/select-by-btn";


/**
 * 费用是否可编辑
 * @see https://pmo.mcd.com.cn/jira/browse/TES-1073
 * @param {*} info
 * @param {*} approvalChains
 *
 * @return {boolean}
 */
export function isExpenseInvoiceEditable(info, approvalChains = []) {
  // #TES-1073 取消该功能
  return false;
  const { status } = info;
  if ([1001, 10011001, 10011002, 10011003, 10011004].includes(status)) {
    return true;
  }

  if (status === 1002) {
    let brmsRemark = "";
    try {
      console.log('isExpenseInvoiceEditable, approvalChains:', approvalChains)
      brmsRemark = approvalChains[0].brmsRemark;
    } catch (e) {}

    if (["财务预审/财务复审", "财务预审", "财务复审"].includes(brmsRemark)) {
      return true;
    }
  }

  return false;
}

class ExpenseAccountTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      auditValues: [],
      showAuditReplyModal: [],
      columns: [
        {
          title: messages("common.sequence") /*序号*/,
          dataIndex: "index",
          width:50,
          // fixed: 'left' // 默认“序号列”固定在左侧 https://pmo.mcd.com.cn/jira/browse/TES-1564
        },
        {
          title: messages("common.expense.type") /*费用类型*/,
          dataIndex: "expenseTypeName",
          width: 150,
          render: (value) => (
            <Popover content={value} overlayStyle={{ maxWidth: 500 }}>
              {value}
            </Popover>
          ),
          sorter: true,
        },
        {
          title: messages("common.date") /*日期*/,
          dataIndex: "createdDate",
          width: 120,
          render: (value) => new Date(value).format("yyyy-MM-dd"),
          sorter: true,
        },
        {
          title: messages("common.currency") /*币种*/,
          dataIndex: "invoiceCurrencyCode",
          width: 50,
        },
        {
          title: messages("common.amount") /*金额*/,
          dataIndex: "amount",
          align: "right",
          width: 100,
          render: (value, record) => {
            let precision1 = currencyPrecisionCal(
              record.invoiceCurrencyCode,
              record.amount
            );
            let precision2 = currencyPrecisionCal(
              record.invoiceCurrencyCode,
              record.originalAmount
            );
            let param1 =
              precision1 !== precision2 ||
              record.actualCurrencyRate !== record.originalActualCurrencyRate;
            let showText = invoiceAmountChange(
              param1,
              value || record.amount,
              record.invoiceCurrencyCode
            );
            return (
              <Popover content={showText} overlayStyle={{ maxWidth: 500 }}>
                {showText}
              </Popover>
            );
          },
        },
        {
          title: messages("common.currency.rate") /*汇率*/,
          dataIndex: "actualCurrencyRate",
          width: 60,
          render: (value, record) =>
            this.filterMoney(value || record.actualCurrencyRate, 2, true),
        },
        {
          title: messages("common.base.currency.amount") /*本位币金额*/,
          dataIndex: "baseAmount",
          align: "right",
          width: 120,
          render: (value, record) =>
            this.filterMoney(
              value || record.baseAmount,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            ),
          sorter: true,
        },
        {
          title: messages("common.base.currency.apportionmentAmount") /*待审批分摊金额*/,
          dataIndex: "apportionmentAmount",
          align: "right",
          width: 120,
          render: (value, record) =>
            value || value === 0 ? this.filterMoney(
              value,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            ) : record.washAmount ? this.filterMoney(
              0,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            ) : this.filterMoney(
              record.baseAmount,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            ),
        },
        {
          title: messages("common.base.currency.washAmount") /*餐饮共享金额*/,
          dataIndex: "washAmount",
          align: "right",
          width: 150,
          render: (value, record) =>
            ['MCD1018', 'MCD1024', 'MCD1221', 'MCD1214', 'MCD1229', 'MCD1053'].includes(record.expenseTypeCode) ? (value || value === 0 ? this.filterMoney(
              value,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            ) : this.filterMoney(
              record.baseAmount,
              queryCurrencyPrecision(props.company.baseCurrency),
              false
            )) : '-',
        },
        // {
        //   title: messages("expense-parent-report.key104") /*摘要信息*/,
        //   dataIndex: "summaryInfo",
        //   width: 100,
        //   render: (value) =>
        //     value ? (
        //       <Popover
        //         content={value}
        //         placement="topLeft"
        //         overlayStyle={{ maxWidth: 350 }}
        //       >
        //         {value}
        //       </Popover>
        //     ) : (
        //       "-"
        //     ),
        // },
        {
          title: messages("common.subjectmatter") /*备注*/,
          dataIndex: "comment",
          width: 70,
          render: (text) => (
            <Popover content={text || "-"} overlayStyle={{ maxWidth: 500 }}>
              {text || "-"}
            </Popover>
          ),
        },
        {
          title: messages("common.attachments") /*附件*/,
          dataIndex: "attachments",
          width: 70,
          render: (attachments) => attachments.length,
        },
        {
          title: messages("expense-parent-report.key105") /*费用归属人*/,
          dataIndex: "owner",
          width: 140,
          render: (value) =>
            this.props.thirdUser ? <Popover
              content={this.props.thirdUser}
              overlayStyle={{ maxWidth: 500 }}
            >
              {this.props.thirdUser}
            </Popover> : value && value.fullName ? (
              <Popover
                content={value.fullName}
                overlayStyle={{ maxWidth: 500 }}
              >
                {value.fullName}
              </Popover>
            ) : (
              "-"
            ),
        },
        // https://pmo.mcd.com.cn/jira/browse/TES-786
        {
          title: "审核状态",
          dataIndex: "approvalStatus",
          width: 150,
          render: (value, record) => {
            const options = [
              { key: "1001", label: "通过" },
              { key: "1002", label: "驳回" },
              { key: "1003", label: "通知" },
            ];
            let defaultValueOption = options.find(
              (item) => item.key === String(value)
            );
            if (!defaultValueOption) {
              if (!this.props.auditable) {
                return "-";
              }
              defaultValueOption = options[0];
            }

            if (!this.props.auditable) {
              return defaultValueOption.label;
            }

            return (
              <div
                onClick={(e) => e.stopPropagation()}
                style={{ width: "100%" }}
              >
                <Select
                  style={{ width: "100%" }}
                  defaultValue={defaultValueOption.key}
                  onClick={(e) => e.stopPropagation()}
                  onChange={(e) => {
                    this.props.onAuditChange([
                      { value: Number(e), key: "approvalStatus", record },
                    ]);
                  }}
                >
                  {options.map((option) => (
                    <Select.Option key={option.key} value={option.key}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </div>
            );
          },
        },
        // https://pmo.mcd.com.cn/jira/browse/TES-786
        {
          title: "审核意见",
          dataIndex: "auditReplyCode",
          width: 200,
          render: (value, record) => {
            // if (!value && !this.props.auditable) {
            //   return "-";
            // }
            let chooserValue = [];
            let showModal = false
            /**
             * reportInvoiceApprovalReqDTOList是正在编辑的列表，
             * 如果正在编辑这行，那么取编辑的值，否则取之前保存的值（value,record)
             */
            const target = this.props.reportInvoiceApprovalReqDTOList.find(
              (item) => item.invoiceOID === record.invoiceOID
            );
            this.state.showAuditReplyModal.some((item) => {
              if (item.invoiceOID === record.invoiceOID) {
                showModal = item.showAuditReplyModal
              }
              return item.invoiceOID === record.invoiceOID
            })
            if (target && target.auditReplyCode) {
              target.auditReplyCode.map((item, index) => {
                chooserValue.push({
                  code: item,
                  reply: target.auditReply[index],
                })
              })
            } else if (value) {
              record.auditReplyCode.map((item, index) => {
                chooserValue.push({
                  code: item,
                  reply: record.auditReply[index],
                })
              })
            }
           
            const isChooserValueEmpty = chooserValue.length === 0
            const codeList = chooserValue.map(item => item.code)
            const replyList = chooserValue.map(item => item.reply)

            let approvalStatus = target ? target.approvalStatus : record.approvalStatus
            if (config.appEnv === 'dev') {
              console.log('审核意见', {approvalStatus, chooserValue, target, record, isChooserValueEmpty, codeList, replyList})
            }
            
            if (!this.props.auditable) {
              const reply = (chooserValue[0] || {}).reply || '-'
              let auditReplyArr = []
              if (record.auditReply && record.auditReply.length > 0) {
                if (typeof record.auditReply === 'string') {
                  auditReplyArr = [record.auditReply]
                } else {
                  auditReplyArr = record.auditReply
                }
              }
              console.log("auditReplyArr", auditReplyArr)
              return (
                <div onClick={(e) => e.stopPropagation()}>
                  <Modal
                  title={'审核意见'}
                  visible={showModal}
                  onCancel={() => this.switchAuditReplyModal(record, false)}
                  onOk={() => this.switchAuditReplyModal(record, false)}
                  width={'800px'}
                >
                  {
                    auditReplyArr.length > 0 ?
                      <div
                        style={{
                          height: '350px',
                          border: '1px solid #F3F3F3',
                          overflow: 'auto'
                        }}
                      >
                        {
                          (auditReplyArr || []).map((reply, index) => {
                            const lastIndex = record.auditReply.length - 1
                            const borderBottom = (index >= 8) && (index === lastIndex) ? '0px' : '1px solid #F3F3F3'
                            return <div
                              title={reply}
                              style={{
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                height: '40px',
                                lineHeight: '40px',
                                width: '100%',
                                textIndent: '1em',
                                cursor: 'pointer',
                                borderBottom: borderBottom
                              }}
                            >
                              {reply}
                            </div>
                          })
                        }
                    </div> : <div
                      style={{
                        height: '350px',
                        lineHeight: '350px',
                        textAlign: 'center',
                        width: '100%',
                        border: '1px solid #F3F3F3',
                        color: '#aaa',
                        fontSize: '16px',
                        letterSpacing: '8px'
                      }}
                    >
                        暂无意见
                    </div>
                  }
                </Modal>
                <If value={auditReplyArr.length > 0}>
                  <Popover title="审核意见" content={
                    <div>
                      {auditReplyArr.map((item, key) => (
                        <p key={key} title={item}
                        style={{
                          borderBottom: '1px solid #e1e1e1'
                        }}>{key + 1}、{item}</p>
                      ))}
                    </div>
                  }
                  >
                    <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={record.approvalStatus ? record.approvalStatus === 1001 ? true : false : true }>查看</a>
                  </Popover>
                </If>
                <If value={auditReplyArr.length === 0}>
                  <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={record.approvalStatus ? record.approvalStatus === 1001 ? true : false : true }>查看</a>
                </If>
                {/* <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={record.approvalStatus ? record.approvalStatus === 1001 ? true : false : true } onClick={() => this.switchAuditReplyModal(record, true)}>查看</a> */}
                </div>
              );
            }
            /**
             * 修改审核意见的Chooser为SelectByBtn，且增加一个查看按钮
             * https://pmo.mcd.com.cn/jira/browse/TES-1904
             */
            return (
              <div
                onClick={(e) => e.stopPropagation()}
                style={{ width: "100%", display: 'flex' }}
              >
                <SelectByBtn
                  buttonType={"primary"}
                  title={'选择'}
                  type="quickReplyDetail"
                  // single
                  labelKey="reply"
                  valueKey="code"
                  value={chooserValue}
                  onChange={(e) => {
                    if (e.length > 0) {
                      const codeArr = e.map((item) => item.code)
                      const replyArr = e.map((item) => item.reply)
                      this.props.onAuditChange([
                        {
                          value: codeArr,
                          key: "auditReplyCode",
                          record,
                        },
                        { value: replyArr, key: "auditReply", record },
                      ]);
                    } else {
                      this.props.onAuditChange([
                        {
                          value: [],
                          key: "auditReplyCode",
                          record,
                        },
                        { value: [], key: "auditReply", record },
                      ]);
                    }
                  }}
                />
                <Modal
                  title={'审核意见'}
                  visible={showModal}
                  onCancel={() => this.switchAuditReplyModal(record, false)}
                  onOk={() => this.switchAuditReplyModal(record, false)}
                  width={'800px'}
                >
                  {
                    replyList.length > 0 ?
                      <div
                        style={{
                          height: '350px',
                          border: '1px solid #F3F3F3',
                          overflow: 'auto'
                        }}
                      >
                        {
                          replyList.map((reply, index) => {
                            const lastIndex = replyList.length - 1
                            const borderBottom = (index >= 8) && (index === lastIndex) ? '0px' : '1px solid #F3F3F3'
                            return <div
                              title={reply}
                              style={{
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                height: '40px',
                                lineHeight: '40px',
                                width: '100%',
                                textIndent: '1em',
                                cursor: 'pointer',
                                borderBottom: borderBottom
                              }}
                            >
                              {reply}
                            </div>
                          })
                        }
                    </div> : <div
                      style={{
                        height: '350px',
                        lineHeight: '350px',
                        textAlign: 'center',
                        width: '100%',
                        border: '1px solid #F3F3F3',
                        color: '#aaa',
                        fontSize: '16px',
                        letterSpacing: '8px'
                      }}
                    >
                        暂无意见
                    </div>
                  }
                </Modal>
                <If value={replyList.length > 0}>
                  <Popover title="审核意见" content={
                    <div>
                      {replyList.map((item, key) => (
                        <p key={key} title={item}
                        style={{
                          borderBottom: '1px solid #e1e1e1'
                        }}>{key + 1}、{item}</p>
                      ))}
                    </div>
                  }
                  >
                    <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={![1002, 1003].includes(approvalStatus)}>查看</a>
                  </Popover>
                </If>
                <If value={replyList.length === 0}>
                  <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={![1002, 1003].includes(approvalStatus)}>查看</a>
                </If>
                {/* <a style={{ display: 'inline-block', marginLeft: '10px', lineHeight: '32px' }} disabled={![1002, 1003].includes(approvalStatus)} onClick={() => this.switchAuditReplyModal(record, true)}>查看</a> */}
              </div>
            )
            // return (
            //   <div
            //     onClick={(e) => e.stopPropagation()}
            //     style={{ width: "100%" }}
            //   >
            //     <Chooser
            //       type="quickReplyDetail"
            //       single
            //       labelKey="reply"
            //       valueKey="code"
            //       value={chooserValue}
            //       onChange={(e) => {
            //         if (e.length > 0) {
            //           this.props.onAuditChange([
            //             {
            //               value: e[0].code,
            //               key: "auditReplyCode",
            //               record,
            //             },
            //             { value: e[0].reply, key: "auditReply", record },
            //           ]);
            //         }
            //       }}
            //     />
            //   </div>
            // );
          },
        },
        // https://pmo.mcd.com.cn/jira/browse/TES-786
        {
          title: "备注",
          dataIndex: "remark",
          width: 150,
          render: (value, record) => {
            if (!value && !this.props.auditable) {
              return "-";
            }
            if (!this.props.auditable) {
              return <Popover content={value}>{value}</Popover>;
            }

            return (
              <Input
                placeholder="请输入"
                onClick={(e) => e.stopPropagation()}
                defaultValue={value}
                onChange={(e) => {
                  this.props.onAuditChange([
                    { value: e.target.value, key: "remark", record },
                  ]);
                }}
              />
            );
          },
        },
        {
          title: messages("common.operation") /*操作*/,
          dataIndex: "operate",
          width: 300,
          render: this.renderExpenseOperate,
        },
      ],
      deleteRecords: [], // 删除中费用
    };
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.auditable) {
      if (nextProps.showExpenseReportInvoices && nextProps.showExpenseReportInvoices.length >= 0) {
        const auditReplyModal = nextProps.showExpenseReportInvoices.map((item) => {
          return {
            invoiceOID: item.invoiceOID,
            showAuditReplyModal: false
          }
        })
        this.setState({
          showAuditReplyModal: auditReplyModal
        })
      }
    }
  }

  componentDidMount = () => {
    if (this.props.showExpenseReportInvoices && this.props.showExpenseReportInvoices.length >= 0) {
      const auditReplyModal = this.props.showExpenseReportInvoices.map((item) => {
        return {
          invoiceOID: item.invoiceOID,
          showAuditReplyModal: false
        }
      })
      this.setState({
        showAuditReplyModal: auditReplyModal
      })
    }
  }

  /**
   * 隐藏指定表格行的审查意见的modal
   * @param {Object} record 
   */
   switchAuditReplyModal = (record, state) => {
    const tempShowModalArr = this.state.showAuditReplyModal.map((item) => {
      if (item.invoiceOID === record.invoiceOID) {
        item.showAuditReplyModal = state
      }
      return item
    })
    this.setState({
      showAuditReplyModal: tempShowModalArr
    })
  }

  //费用的操作列
  renderExpenseOperate = (text, record) => {
    let { handleView, handleEdit, readOnly, info, approvalChains } = this.props;
    const { deleteRecords } = this.state;
    let isSubsidy = record.expenseTypeSubsidyType === 1; //是否为差旅补贴费用
    // const editButton = isExpenseInvoiceEditable(info, approvalChains) ? (
    //   <Button type="link" ghost onClick={() => handleEdit(record)}>
    //     编辑
    //   </Button>
    // ) : null;
    const editButton = <a
      style={{ color: record.ableToCreatedManually ? "" : "#bfbfbf" }}
      onClick={() => this.handleEdit(record)}
    >
      编辑
    </a>
    return readOnly ? (
      <span>
        <a onClick={() => handleView(record)}>
          {messages("common.view") /*查看*/}
          {record.status === 1002 &&
            `(${messages("expense-parent-report.key5" /*已驳回*/)})`}
        </a>
        {/* <span className="ant-divider" /> */}
        {/* {editButton} */}
      </span>
    ) : (
      <span>
        {editButton}
        <span className="ant-divider" />
        <a
          style={{ color: record.ableToCreatedManually ? "" : "#bfbfbf" }}
          onClick={(e) => this.copyInvoice(e, record)}
          disabled={['MCD1018', 'MCD1024', 'MCD1214', 'MCD1221', 'MCD1229', 'MCD1053'].includes(record.expenseTypeCode)}
        >
          {messages("common.copy") /*复制*/}
        </a>
        <span className="ant-divider" />
        <Condition>
          <If value={deleteRecords.some((item) => item === record.invoiceOID)}>
            <Icon
              type="loading"
              className="default-color-font"
              style={{ marginRight: 5 }}
            />
            <a onClick={(e) => e.stopPropagation()}>
              {
                isSubsidy
                  ? messages("common.delete")
                  : messages("expense-parent-report.key100") /*退回账本*/
              }
            </a>
          </If>
          <Else>
            <Popconfirm
              onConfirm={() => this.deleteExpense(record)}
              title={
                isSubsidy
                  ? messages("common.confirm.delete")
                  : messages("expense-parent-report.key99") /*是否退回账本*/
              }
            >
              <a onClick={(e) => e.stopPropagation()}>
                {
                  isSubsidy
                    ? messages("common.delete")
                    : messages("expense-parent-report.key100") /*退回账本*/
                }
              </a>
            </Popconfirm>
          </Else>
        </Condition>
      </span>
    );
  };

  //处理显示列
  filterColumns = () => {
    const { info } = this.props;
    let { columns } = this.state;
    if (info && info.children && info.children.length > 0) {
      console.log("有子单");
      //有子单
      removeArryItem(
        columns,
        columns.filter((item) => item.dataIndex === "splitType")[0]
      );
      removeArryItem(
        columns,
        columns.filter((item) => item.dataIndex === "statusView")[0]
      );
      let expenseTypeColumn = {
        title: messages("common.invoice.type") /*发票类型*/,
        dataIndex: "splitType",
        width: "8%",
        render: (value, row) => {
          return {
            children: row.splitName,
            props: {},
          };
        },
      };
      let statusColumn = {
        title: messages("common.column.status") /*状态*/,
        dataIndex: "statusView",
        width: "8%",
        render: (value, row) => {
          return {
            children: row.statusViewShow,
            props: {},
          };
        },
      };
      columns.unshift(expenseTypeColumn);
      columns.push(statusColumn);
    }
    // console.log("columns", columns)
    return columns;
  };

  //费用复制
  copyInvoice = (e, record) => {
    e.preventDefault();
    e.stopPropagation();
    if (!record.ableToCreatedManually) {
      message.error(messages("expense-parent-report.key163") /*不可复制*/);
      return !1;
    }
    expenseService
      .validateCopyInvoice({ invoiceOID: record.invoiceOID })
      .then(() => {
        this.props.handleCopy(record);
      })
      .catch((e) => {
        errorMessage(e.response);
      });
  };

  //费用删除（退回账本）
  deleteExpense = (record) => {
    const { info } = this.props;
    let { deleteRecords } = this.state;
    deleteRecords.push(record.invoiceOID);
    this.setState({ deleteRecords });
    expenseReportService
      .removeExpense(info.expenseReportOID, record.invoiceOID)
      .then(() => {
        let isSubsidy = record.expenseTypeSubsidyType === 1; //是否为差旅补贴费用
        message.success(
          isSubsidy
            ? messages("common.delete.successful")
            : messages("expense-parent-report.key102") /*费用已回到我的账本*/
        );
        removeArryItem(deleteRecords, record.invoiceOID);
        this.setState({ deleteRecords });
        this.props.handleDelete(isSubsidy);
      })
      .catch((e) => {
        errorMessage(e.response);
        removeArryItem(deleteRecords, record.invoiceOID);
        this.setState({ deleteRecords });
      });
  };

  //渲染列表展开信息
  renderAllExpandedRow = (record) => {
    let result = [];
    let infoRes = [];
    let types = record.invoiceLabels || [];
    let lastIndex = -1;
    types.map((label, index) => {
      if (label.level !== "INFO") {
        result.push(this.renderExpandedRow(label, index));
      } else {
        lastIndex = label.name;
        infoRes.push(<span>{label.name}/</span>);
      }
    });
    let infoLength = infoRes.length;
    if (infoLength > 0) {
      infoRes[infoLength - 1] = <span>{lastIndex}</span>;
    }
    result.push(infoRes);
    return result.length > 0 ? result : null;
  };

  //渲染列表展开信息 - 行信息
  renderExpandedRow = (type, index) => {
    let className =
      type.level === "WARN"
        ? "warning-expanded-row"
        : type.level === "ERROR"
        ? "error-expand-row"
        : "";
    let content = type.name;
    type.toast && (content += `：${type.toast}`);
    return (
      <div className={`expanded-row-list ${className}`} key={index}>
        <Popover content={content} placement="topLeft">
          {content}
        </Popover>
      </div>
    );
  };

  renderClass = (record) => {
    let isWarn = false;
    record.invoiceLabels &&
      record.invoiceLabels.map((label) => {
        (label.level === "WARN" || label.level === "ERROR") && (isWarn = true);
      });
    record.checkResultStatus && (isWarn = true);
    return (record.invoiceLabels && record.invoiceLabels.length > 0) ||
      record.checkResultStatus
      ? isWarn
        ? "rejected-expense"
        : ""
      : "row-expand-display-none";
  };

  //渲染表格头
  renderTableTitle = () => {
    const {
      info,
      filterCondition,
      expenseRowSelection,
      filterData,
      showExpenseReportInvoices,
      filterDataSum,
      expenseReportStatus,
    } = this.props;
    let conditions =
      filterCondition.ownerOID.length +
      filterCondition.expenseTypeOID.length +
      filterCondition.date.length;
    let baseCurrencyPrecision = queryCurrencyPrecision(info.baseCurrency);
    let showExpenseReportInvoiceSum = 0;
    let hasSelectedInvoice = expenseRowSelection.selectedRowKeys.length > 0;
    let showSelectedInvoiceNumber = hasSelectedInvoice
      ? expenseRowSelection.selectedRowKeys.length
      : showExpenseReportInvoices.length;
    let totalApportionmentAmount = 0;
    let totalWashAmount = 0;
    //如果已有费用选择，则显示已选费用的数量及总数;否则显示所有费用的数量及总数
    showExpenseReportInvoices.map((invoice, index) => {
      invoice.index = index + 1;
      if (hasSelectedInvoice) {
        expenseRowSelection.selectedRowKeys.map((OID) => {
          if (invoice.invoiceOID === OID) {
            showExpenseReportInvoiceSum = addCalculate(
              showExpenseReportInvoiceSum,
              invoice.baseAmount.toFixed(baseCurrencyPrecision)
            );
            totalApportionmentAmount = addCalculate(
              totalApportionmentAmount,
              invoice.apportionmentAmount || invoice.apportionmentAmount === 0 ? invoice.apportionmentAmount.toFixed(baseCurrencyPrecision) : invoice.washAmount ? 0 : invoice.baseAmount.toFixed(baseCurrencyPrecision)
            );
            totalWashAmount = addCalculate(
              totalWashAmount,
              ['MCD1018', 'MCD1024', 'MCD1221', 'MCD1214', 'MCD1229', 'MCD1053'].includes(invoice.expenseTypeCode) ? invoice.washAmount || invoice.washAmount === 0 ? invoice.washAmount.toFixed(baseCurrencyPrecision) : invoice.baseAmount.toFixed(baseCurrencyPrecision) : 0
            );
          }
        });
      } else {
        showExpenseReportInvoiceSum = addCalculate(
          showExpenseReportInvoiceSum,
          invoice.baseAmount.toFixed(baseCurrencyPrecision)
        );
        totalApportionmentAmount = addCalculate(
          totalApportionmentAmount,
          invoice.apportionmentAmount || invoice.apportionmentAmount === 0 ? invoice.apportionmentAmount.toFixed(baseCurrencyPrecision) : invoice.washAmount ? 0 : invoice.baseAmount.toFixed(baseCurrencyPrecision)
        );
        totalWashAmount = addCalculate(
          totalWashAmount,
          ['MCD1018', 'MCD1024', 'MCD1221', 'MCD1214', 'MCD1229', 'MCD1053'].includes(invoice.expenseTypeCode) ? invoice.washAmount || invoice.washAmount === 0 ? invoice.washAmount.toFixed(baseCurrencyPrecision) : invoice.baseAmount.toFixed(baseCurrencyPrecision) : 0
        );
      }
    });
    let nullCondition = {
      owner: [],
      ownerOID: [],
      expenseType: [],
      expenseTypeOID: [],
      date: [],
    };
    return (
      <div className="expense-table-title">
        <If value={conditions}>
          <div className="filter-condition">
            {filterCondition.owner.length
              ? messages("expense-parent-report.key173") /*归属人*/ +
                `=${filterCondition.owner.join("、")}；`
              : ""}
            {filterCondition.expenseType.length
              ? messages("common.expense.type") /*费用类型*/ +
                `=${filterCondition.expenseType.join("、")}；`
              : ""}
            {filterCondition.date.length
              ? messages("common.happened.date") /*发生日期*/ +
                `=${filterCondition.date.join("～").split(" ")[0]}`
              : ""}
            &nbsp;&nbsp;
            <a
              className="default-color-font"
              onClick={() => this.props.handleClearFilter(nullCondition)}
            >
              {messages("expense-parent-report.key174") /*清空筛选*/}
            </a>
          </div>
        </If>
        {
          hasSelectedInvoice
            ? messages("common.has.selected") /*已选*/
            : messages("common.number") /*数量*/
        }
        ：&nbsp;
        <b>
          {conditions ? filterData.length : showSelectedInvoiceNumber}&nbsp;
          <span className="ant-divider" />
        </b>
        &nbsp;
        {messages("common.total.amount") /*总金额*/}：&nbsp;
        <b>
          {info.baseCurrency}{" "}
          {this.filterMoney(
            conditions ? filterDataSum : showExpenseReportInvoiceSum,
            baseCurrencyPrecision
          )}
        </b>
        &nbsp;&nbsp;
        {messages("common.base.currency.totalApportionmentAmount") /*合计待审批分摊金额*/}：&nbsp;
        <b>
          {info.baseCurrency}{" "}
          {this.filterMoney(
            conditions ? filterDataSum : totalApportionmentAmount,
            baseCurrencyPrecision
          )}
        </b>
        &nbsp;&nbsp;
        {messages("common.base.currency.washAmount") /*餐饮共享金额*/}：&nbsp;
        <b>
          {totalWashAmount ? info.baseCurrency : ''}{" "}
          {totalWashAmount ? this.filterMoney(
            conditions ? filterDataSum : totalWashAmount,
            baseCurrencyPrecision
          ) : '-'}
        </b>
        <If
          value={
            ["1001", "10011001", "10011002", "10011003", "10011004"].indexOf(
              expenseReportStatus.value
            ) === -1
          }
        >
          <a className="f-right" onClick={this.props.toggleCalendarMode}>
            <Icon type="calendar" />
            {messages("expense-parent-report.key175") /*查看日历*/}
          </a>
        </If>
      </div>
    );
  };

  render() {
    const {
      loading,
      readOnly,
      pageFrom,
      form,
      profile,
      filterData,
      showExpenseReportInvoices,
      expenseRowSelection,
      filterCondition,
      batchApportion,
    } = this.props;
    let conditions =
      filterCondition.ownerOID.length +
      filterCondition.expenseTypeOID.length +
      filterCondition.date.length;
    return (
      <div className="expense-account-table" data-description="费用行">
        <CustomTable
          allColumns={this.filterColumns()}
          localKey="expense-account-column"
          tableOption={{
            rowKey: "invoiceOID",
            size: "middle",
            loading,
            hasFixed: true,
            scroll: { x: 2050 },
            // scroll: { x: 1550 },
            rowSelection:
              (!readOnly &&
                (window.ISIE9 ||
                  (form["customFormPropertyMap"] &&
                    form["customFormPropertyMap"][
                      "report.property.pay.multi.lines"
                    ] === "true") ||
                  batchApportion)) ||
              (pageFrom === "approveView" &&
                typeof profile["app.approval.reject.batch.disabled"] ===
                  "boolean" &&
                !profile["app.approval.reject.batch.disabled"])
                ? expenseRowSelection
                : null,
            pagination: false,
            columns: this.filterColumns(),
            bordered: true,
            dataSource: conditions ? filterData : showExpenseReportInvoices,
            expandedRowRender: this.renderAllExpandedRow,
            rowClassName: this.renderClass,
            onChange: this.props.handleChangeInvoiceColumns,
            title: () => this.renderTableTitle(),
            onRow: (record) => ({
              onClick: () => this.props.handleRowClick(record),
            }),
          }}
        />
      </div>
    );
  }
}

ExpenseAccountTable.propsType = {
  loading: React.PropTypes.bool,
  step: React.PropTypes.number,
  readOnly: React.PropTypes.bool,
  pageFrom: React.PropTypes.string,
  info: React.PropTypes.object, //报销单详情
  approvalChains: React.PropTypes.array, // 审批链
  form: React.PropTypes.object, //表单详情
  batchApportion: React.PropTypes.bool, //开启批量分摊
  handleView: React.PropTypes.func, //查看费用详情
  handleCopy: React.PropTypes.func, //复制费用
  handleEdit: React.PropTypes.func, //编辑费用
  handleDelete: React.PropTypes.func, //删除费用
  handleChangeInvoiceColumns: React.PropTypes.func, //费用列表改变
  onAuditChange: React.PropTypes.func, // 审核意见、审核状态修改
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
  };
}

export default connect(mapStateToProps)(ExpenseAccountTable);
